<template>
  <div class="top">
    <el-card class="tecard">
      <div class="tediv">
        <div class="tebutton">
          <el-form :inline="true">
            <el-form-item>
              <el-input
                placeholder="请输入教师姓名"
                v-model="keyword"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleQuery"
                >搜 索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="tebutton">
          <!-- <div class="InsertExcel"> -->
          <el-upload
            class="tebutt"
            ref="upload"
            accept=".xls, .xlsx"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-change="upload"
            :show-file-list="false"
            :auto-upload="false"
          >
            <!-- 导入的excel表格和展示的表头名el-table的prop对应-->
            <el-button
              slot="trigger"
              size="large"
              icon="el-icon-upload2"
              type="success"
              >导 入</el-button
            >
          </el-upload>
        </div>
        <div class="tebutton">
          <el-button
            @click="ExportExcel"
            class="tebutt"
            icon="el-icon-printer"
            type="success"
            >导 出</el-button
          >
        </div>
        <div class="tebutton">
          <el-button
            type="success"
            @click="handleAdd"
            icon="el-icon-plus"
            class="tebutt"
            >添 加</el-button
          >
        </div>
      </div>
    </el-card>
    <el-card>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column fixed label="序号" align="center">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column
          label="工号"
          align="center"
          property="teacherInfo.workNumber"
        ></el-table-column>
        <el-table-column
          label="教师角色"
          align="center"
          property="roleName"
        ></el-table-column>
        <el-table-column
          label="教师名称"
          align="center"
          property="teacherInfo.teacherName"
        ></el-table-column>
        <el-table-column
          label="性别"
          align="center"
          property="teacherInfo.sex"
        ></el-table-column>
        <el-table-column
          label="身份证号码"
          align="center"
          property="teacherInfo.idNumber"
        ></el-table-column>
        <el-table-column
          label="学院号"
          align="center"
          property="academyName"
        ></el-table-column>
        <el-table-column
          label="手机号"
          align="center"
          property="teacherInfo.phoneNumber"
        ></el-table-column>
        <el-table-column
          label="QQ号码"
          align="center"
          property="teacherInfo.qqNumber"
        ></el-table-column>
        <el-table-column
          label="微信号码"
          align="center"
          property="teacherInfo.weChat"
        ></el-table-column>
        <el-table-column
          label="家庭地址"
          align="center"
          property="teacherInfo.address"
        ></el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-dialog :visible.sync="dialogFormVisible">
          <el-form :model="form" :rules="rules" ref="formDemo" class="formadd">
            <!-- <el-form-item label="工号:" :label-width="formLabelWidth" v-show="false">
              <el-input v-model="form.workNum" autocomplete="off"></el-input>
            </el-form-item> -->
            <el-form-item
              label="教师名:"
              :label-width="formLabelWidth"
              prop="teacherName"
            >
              <el-input
                v-model="form.teacherName"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="角色:"
              :label-width="formLabelWidth"
              prop="roleName"
            >
              <el-select v-model="form.roleName" placeholder="请选择角色">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="性别:"
              :label-width="formLabelWidth"
              prop="sex"
            >
              <el-radio v-model="form.sex" label="男">男</el-radio>
              <el-radio v-model="form.sex" label="女">女</el-radio>
            </el-form-item>
            <el-form-item
              label="身份证号码:"
              :label-width="formLabelWidth"
              prop="idNumber"
            >
              <el-input v-model="form.idNumber" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              label="学院名称:"
              :label-width="formLabelWidth"
              prop="academyName"
            >
              <el-select v-model="form.academyNum" placeholder="请选择学院">
                <el-option
                  v-for="(item, index) in collage"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="手机号:"
              :label-width="formLabelWidth"
              prop="phoneNumber"
            >
              <el-input
                v-model="form.phoneNumber"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="QQ号码:"
              :label-width="formLabelWidth"
              prop="qqNumber"
            >
              <el-input v-model="form.qqNumber" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              label="微信号码:"
              :label-width="formLabelWidth"
              prop="weChat"
            >
              <el-input v-model="form.weChat" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              label="家庭地址:"
              :label-width="formLabelWidth"
              prop="address"
            >
              <el-input v-model="form.address" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取 消</el-button>
            <el-button type="primary" @click="handleSave">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <div>
        <el-pagination
          class="defenye"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageIndex"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.count"
          background
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as XLSX from "xlsx/xlsx.mjs";
import {
  GetTeacherList,
  UpdateTeacher,
  AddTeacher,
  DeleteTeacher,
  QueryTeacher,
} from "@/api/teacherapi";
import { GetAcademyList } from "@/api/academyapi";
export default {
  data() {
    return {
      page: {
        pageIndex: 1,
        pageSize: 10,
        rowsTotal: 100,
      },
      collage: [],
      options: [
        {
          value: "辅导员",
          label: "辅导员",
        },
        {
          value: "教师",
          label: "教师",
        },
      ],
      currentIndex: 0,
      keyword: "",
      tableData: [],
      academytable: [],
      dialogFormVisible: false,
      formLabelWidth: "120px",
      form: {
        id: 0,
        // workNumber:"",
        roleName: "",
        teacherName: "",
        academyName: "",
        sex: "",
        idNumber: "",
        academyNum: "",
        phoneNumber: "",
        qqNumber: "",
        weChat: "",
        address: "",
      },
      rules: {
        teacherName: [
          {
            required: true,
            trigger: "blur",
            message: "请输入教师姓名",
          },
        ],
        roleName: [
          {
            required: true,
            trigger: "blur",
            message: "请输入角色名称",
          },
        ],
        sex: [
          {
            required: true,
            trigger: "blur",
            message: "请选择性别",
          },
        ],
        idNumber: [
          {
            required: true,
            trigger: "blur",
            message: "请输入身份证号",
          },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: "请输入正确的身份证号码",
          },
        ],
        academyName: [
          {
            required: true,
            trigger: "blur",
            message: "请输入学院名称",
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          { min: 11, max: 11, message: "请输入11位手机号码", trigger: "blur" },
          {
            pattern:
              /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: "请输入正确的手机号码",
          },
        ],
        qqNumber: [
          { required: true, message: "请输入QQ号码", trigger: "blur" },
        ],
        weChat: [
          { required: true, message: "请输入微信号码", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入微信号码", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.GetList();
    this.GetAcademy();
  },
  methods: {
    //分页
    handleCurrentChange(val) {
      this.page.pageIndex = val > 0 ? val : 1;
      this.GetList();
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.GetList();
    },
    //获取教师列表
    GetList() {
      let params = {
        keyword: this.keyword,
        pageIndex: this.page.pageIndex,
        pageSize: this.page.pageSize,
      };
      GetTeacherList(params).then((res) => {
        console.log(res);
        if (res.code === 200) {
          this.$message({
            message: "已刷新数据",
            type: "success",
          });
          this.tableData = res.data;
          this.page.count = res.page.count;
        }
      });
    },
    //获取学院列表
    GetAcademy() {
      GetAcademyList().then((res) => {
        res.data.forEach((item) => {
          var obj = { label: item.academyName, value: item.academyNum };
          this.collage.push(obj);
          console.log(this.collage);
        });
      });
    },
    //查询
    handleQuery() {
      if (this.keyword == "") {
        this.$message.warning("查询条件不能为空");
        this.keyword = "";
        this.GetList();
        return;
      }
      console.log("你输入的查询条件:" + this.keyword);
      QueryTeacher(this.keyword).then((res) => {
        this.tableData = res.data;
        console.log(this.tableData);
        if(this.tableData.length === 0){
          this.$message({
              message: "该数据不存在,请根据教师名称进行查询",
              type: "warning",
            });
        }
      });
    }, 
    //添加
    handleAdd() {
      this.dialogFormVisible = true;
      this.form.id = 0;
      (this.form.roleName = ""),
        (this.form.teacherName = ""),
        (this.form.sex = ""),
        (this.form.idNumber = ""),
        (this.form.academyNum = ""),
        (this.form.phoneNumber = ""),
        (this.form.qqNumber = ""),
        (this.form.weChat = ""),
        (this.form.address = "");
    },
    //编辑
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.form.roleName = row.roleName;
      this.form.teacherName = row.teacherInfo.teacherName;
      this.form.sex = row.teacherInfo.sex;
      this.form.idNumber = row.teacherInfo.idNumber;
      this.form.academyNum = row.teacherInfo.academyNum;
      this.form.phoneNumber = row.teacherInfo.phoneNumber;
      this.form.qqNumber = row.teacherInfo.qqNumber;
      this.form.weChat = row.teacherInfo.weChat;
      this.form.address = row.teacherInfo.address;
      this.form.currentIndex = index;
      this.form.id = row.teacherInfo.id;
      console.log(index, row);
    },
    //取消
    handleCancel() {
      this.dialogFormVisible = false;
    },
    // 模态框内的确定按钮
    handleSave() {
      this.dialogFormVisible = false;
      if (this.form.id === 0) {
        delete this.form.id;
        console.log(this.form);
        AddTeacher(this.form).then((data) => {
          console.log(data);
          if (data.code === 402) {
            this.$message({
              message: data.msg,
              type: "warning",
            });
          }
          if (data.code === 200) {
            this.$message({
              message: data.msg,
              type: "success",
            });
            this.$router.go(0);
          }
        });
      } else {
        UpdateTeacher(this.form.id, this.form).then((data) => {
          console.log(data);
          this.$router.go(0);
        });
      }
    },
    //删除
    handleDelete(index, row) {
      // 删除时获得当前表数组中的下标
      this.currentIndex = index;
      // 弹框提示
      this.$confirm("此操作将永久删除该课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          DeleteTeacher(row.teacherInfo.id).then((res) => {
            if (res.code === 200) {
              this.tableData.splice(index, 1);
              this.$message.success("删除成功");
            } else {
              this.$message({
                type: "error",
                message: "删除失败",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    upload(file, fileList) {
      console.log(file, "file");
      console.log(fileList, "fileList");
      let files = { 0: file.raw }; // 取到File
      this.readExcel(files);
    },
    readExcel(files) {
      // 表格导入
      var that = this;
      console.log(files);
      if (files.length <= 0) {
        // 如果没有文件名
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }

      const fileReader = new FileReader();
      //onload 当读取操作成功完成时调用
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          // console.log('数据   '+data);
          const workbook = XLSX.read(data, {
            type: "binary",
          });
          console.log(workbook);
          const wsname = workbook.SheetNames[0]; // 取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); // 生成json表格内容
          console.log(ws, "ws是表格里的数据，且是json格式");

          for (var i = 0; i < ws.length; i++) {
            this.tableData.push(ws[i]);
          }

          console.log(this.tableData, "tableData");
          // 重写数据
          this.$refs.upload.value = "";
        } catch (e) {
          console.log(e);
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    //导出数据
    ExportExcel() {
      const headers = [
        {
          title: "工号",
          key: "workNum",
        },
        {
          title: "教师名",
          // dataIndex: 'grade',
          key: "teacherName",
        },
        {
          title: "性别",
          key: "Sex",
        },
        {
          title: "身份证号码",
          key: "IDnumber",
        },
        {
          title: "学院号",
          key: "collageNum",
        },
        {
          title: "手机号",
          key: "Phone",
        },
        {
          title: "QQ号",
          key: "qq",
        },
        {
          title: "微信号",
          key: "WeChat",
        },
        {
          title: "家庭住址",
          key: "adress",
        },
      ];
      console.log(this.tableData);
      this.exportExcel(headers, this.tableData, "教师人员名单.xlsx");
    },
    exportExcel(headers, data, fileName = "导出结果.xlsx") {
      // console.log(data);
      const _headers = headers
        .map((item, i) =>
          Object.assign(
            {},
            {
              key: item.key,
              title: item.title,
              position: String.fromCharCode(65 + i) + 1,
            }
          )
        )
        .reduce(
          (prev, next) =>
            Object.assign({}, prev, {
              [next.position]: { key: next.key, v: next.title },
            }),
          {}
        );

      const _data = data
        .map((item, i) =>
          headers.map((key, j) =>
            Object.assign(
              {},
              {
                content: item[key.key],
                position: String.fromCharCode(65 + j) + (i + 2),
              }
            )
          )
        )
        // 对刚才的结果进行降维处理（二维数组变成一维数组）
        .reduce((prev, next) => prev.concat(next))
        // 转换成 worksheet 需要的结构
        .reduce(
          (prev, next) =>
            Object.assign({}, prev, { [next.position]: { v: next.content } }),
          {}
        );
      // 合并 headers 和 data
      console.log(_data);
      const output = Object.assign({}, _headers, _data);
      // 获取所有单元格的位置
      const outputPos = Object.keys(output);
      // 计算出范围 ,["A1",..., "H2"]
      const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`;

      // 构建 workbook 对象
      const wb = {
        SheetNames: ["mySheet"],
        Sheets: {
          mySheet: Object.assign({}, output, {
            "!ref": ref,
            "!cols": [
              { wpx: 45 },
              { wpx: 100 },
              { wpx: 200 },
              { wpx: 80 },
              { wpx: 150 },
              { wpx: 100 },
              { wpx: 300 },
              { wpx: 300 },
            ],
          }),
        },
      };
      // console.log(wb);
      // 导出 Excel
      XLSX.writeFile(wb, fileName);
    },
  },
};
</script>
<style scoped>
.formadd > .el-form-item > .el-form-item__label {
  font-weight: bolder !important;
  font-size: 18px;
}
.tediv {
  display: flex;
  float: left;
}
.tebutton {
  margin-left: 10px;
  float: right;
}
.tecard {
  height: 80px;
  margin-bottom: 1px;
}
.tebutton > .el-form-item > .el-button--primary {
  height: 100px;
}
.tebutt {
  margin-top: 1px;
}
.tefenye {
  margin-top: 30px;
  margin-bottom: 10px;
}
</style>
